#!/usr/bin/env python

# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Street Identity Demo Attribute Provider."""

import fix_path #@UnusedImport

from google.appengine.dist import use_library
use_library('django', '1.2')

import os

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template

import logging
from UserString import MutableString

from lib import utils, dbinit
from lib import authn
from lib.loggable import loggable
from lib import oauth2client #@UnresolvedImport
from lib import streetaddress_api
from lib import streetaddress_entry

import model
import app_params as application_params
import account #@UnresolvedImport
import postcard #@UnresolvedImport

__author__ = "Maciej Machulak"
__maintainer__ = "Maciej Machulak"
__email__ = "mmachulak@google.com"

__copyright__ = "Copyright 2011, Google Inc."
__license__ = "Apache License 2.0"
__version__ = "0.1"
__status__ = "Prototype"
 
class MainHandler(webapp.RequestHandler):

    """Serves the main page of the web app."""
    @authn.redirect_logged_user('/account')
    @loggable('main page')  
    def get(self, *args): 

      continue_to = self.request.get(application_params.Http.CONTINUE_TO)
      values = {}
      if continue_to and len(continue_to) > 0:
        values = {
            continue_to: continue_to
            }
      path = os.path.join(os.path.dirname(__file__), 'templates/index.html')
      self.response.out.write(template.render(path, values))
      
class SignInHandler(webapp.RequestHandler):
    
    """Redirects the user to the correct identity provider."""
    @loggable('sign in')         
    def get(self):

      continue_to = self.request.get(application_params.Http.CONTINUE_TO)
      state_id = None
      if continue_to is not None and len(continue_to) > 0:
        state = model.State(
              id = utils.random(),
              continue_to = continue_to)
        state.put() 
        state_id = state.id 
      sign_in_url = self.__create_sign_in_url(state_id)
      logging.debug('redirecting user to %s' % sign_in_url)
      self.redirect(sign_in_url)
    
    def __create_sign_in_url(self, state = None):
      sign_in_url = MutableString()
      sign_in_url += application_params.Config.authz_endpoint
      sign_in_url += '?response_type=code'
      sign_in_url += '&client_id='
      sign_in_url += application_params.Config.client_id
      sign_in_url += '&redirect_uri='
      sign_in_url += application_params.Config.redirect_uri
      sign_in_url += '&scope='
      sign_in_url += ','.join(application_params.Config.scope)
      if state:
        sign_in_url += '&state='
        sign_in_url += state
      return sign_in_url.__str__()    
      
class SignOutHandler(webapp.RequestHandler):
  
    """Logs out the user from the application - deletes the session for the user."""    
    @authn.login_required
    @loggable('sign out')     
    def get(self):
      
      # Delete the session for the user
      session = self.session
      session.delete()
      self.response.headers.add_header('set-cookie', application_params.Http.SESSION_ID + '=')
      
      # Redirect the user to main page      
      self.redirect('/')      


routes = [('/', MainHandler),
          ('/sign_in', SignInHandler),
          ('/sign_out', SignOutHandler),
          
          ('/account', account.AccountHandler),
          ('/account/delete', account.DelAddressHandler),
          ('/account/verify', account.VerifyAddressHandler),
                   
          ('/postcards', postcard.PostcardHandler),
          
          ('/oauth/redirect', oauth2client.RedirectHandler),
          
          ('/street_address_entry', streetaddress_entry.RequestAddressHandler),
          ('/api/street_address/(.*)', streetaddress_api.AddressHandler),
          
          ('/db_setup', dbinit.DBInitHandler)]
    
application = webapp.WSGIApplication(routes,debug=True)
  
def main():
    logging.getLogger().setLevel(logging.DEBUG)
    run_wsgi_app(application)

if __name__ == "__main__":
  main()












